import {loadEnv} from 'vite'
import type { UserConfig, ConfigEnv, ProxyOptions } from 'vite'
import vue from '@vitejs/plugin-vue'
import {resolve} from 'path'
import { svgBuilder } from '/@/components/icon/svg/index'
import { tr } from 'element-plus/es/locale'

// https://vitejs.dev/config/
const viteConfig = ({mode}: ConfigEnv): UserConfig => {

    const {VITE_PORT, VITE_OPEN, VITE_BASE_PATH, VITE_OUT_DIR, VITE_PROXY_URL} = loadEnv(mode, process.cwd())

    const pathResolve = (dir: string): any => {
        return resolve(__dirname, '.', dir)
    }

    const alias: Record<string, string> = {
        "@": resolve(__dirname, 'src'),
        '/@': pathResolve('./src/'),
        assets: pathResolve('./src/assets')
    }
    let proxy: Record<string, string | ProxyOptions> = {}
    if (VITE_PROXY_URL) {
        proxy = {
            '/': {
                target: VITE_PROXY_URL,
                changeOrigin: true,
            },
        }
    }
    return {
        root: process.cwd(),
        base: VITE_BASE_PATH,
        server: {
            host:true,
            port: parseInt(VITE_PORT),
            open: VITE_OPEN !== 'false',
            proxy: proxy
        },
        plugins: [
            vue(),
            svgBuilder('./src/assets/icons/')
        ],
        resolve: {
            alias: alias,
            extensions: ['.js', '.vue', '.json', '.ts'] // 使用路径别名时想要省略的后缀名，可以自己 增减
        },
        optimizeDeps: {
            include: []
        },

        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: '@import "./src/styles/global.scss";'
                }
            }
        },

        build: {
            outDir: VITE_OUT_DIR,
            cssCodeSplit: false,
            sourcemap: false,
            emptyOutDir: true,
            chunkSizeWarningLimit: 1500,
            rollupOptions: {
                // 指定生产打包入口文件为index.htm
                input: {
                    main: resolve(__dirname, 'index.html'),
                },

                // // 确保外部化处理那些你不想打包进库的依赖
                // external: ['vue', 'element-plus'],
                // output: {
                //   // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
                //   globals: {
                //     vue: 'Vue', //报错：Failed to resolve module specifier "vue". Relative references must start with either
                //     'element-plus': 'ElementPlus',
                //   }
                // }
            }
        }
    }
}

export default viteConfig
